﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Seven.Entity;
using Seven.DataModel.RepositoryModels.UserAbout;
using Seven.Tools.Extension;
using Seven.Web.IntelligentQuery.Model;
using Seven.Web.IntelligentQuery.Extensions;

namespace Seven.MsSql.Repositories
{
    public partial class SysUserMenuPermissionRepository
    {
        /// <summary>
        /// 根据用户ID获取该用户的菜单权限集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public IEnumerable<SysUserMenuPermission> GetUserMenuPermissions(int userId)
        {
            return this.Entities().Where(w => w.UserID == userId).ToArray();
        }

        /// <summary>
        /// 获取指定用户的限定菜单权限列表数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="menuIds">菜单ID集合</param>
        /// <param name="filterUncheck">是否过滤掉“未选中”数据</param>
        /// <returns></returns>
        public IEnumerable<UserMenuPermissionGridModel> UserMenuPermissionGrid(int userId, IEnumerable<int> menuIds, bool filterUncheck)
        {
            var userMenuPermission = this.Entities().Where(w => w.UserID == userId);
            if (filterUncheck) { userMenuPermission = userMenuPermission.Where(w => w.Check); }
            var menuPermission = new SysMenuPermissionRepository(this.dbContext).Entities();
            var menu = new SysMenuRepository(this.dbContext).Entities();

            var query = (from a in userMenuPermission
                         join b in menuPermission on a.MenuPermissionID equals b.ID into ab
                         from menuPermissionInfo in ab.DefaultIfEmpty()
                         join c in menu on menuPermissionInfo.MenuID equals c.ID
                         select new
                         {
                             a.ID,
                             a.UserID,
                             a.Check,
                             a.Indeterminate,
                             a.MenuPermissionID,
                             MenuPermissionName = menuPermissionInfo.Name,
                             MenuPermissionSortNumber = menuPermissionInfo.SortNumber,
                             MenuID = c.ID,
                             MenuSortNumber = c.SortNumber
                         });

            if (menuIds.Count() > 0) { query = query.Where(w => menuIds.Contains(w.MenuID)).OrderBy(o => o.MenuSortNumber).ThenBy(o => o.MenuPermissionSortNumber); }
            else { query = query.OrderBy(o => o.MenuSortNumber).ThenBy(o => o.MenuPermissionSortNumber); }

            return query.ToArray().Select(s => s.CastTo<UserMenuPermissionGridModel>(false));
        }
    }
}
